import {mapState} from 'vuex'
import {orderMixins} from '../../core/mixins'
import {GET_INDEX, ORDER_TAKING,VERSION,EDIT_WORK_STATUS} from '../../assets/js/api'
import transfer from '../../core/transfer'

export default {
  name: 'index',
  beforeRouteEnter(to, from, next) {
    if ($prod) {
      StatusBar.show();
    }
    next()
  },
  mixins: [orderMixins],
  data() {
    return {
      orders_week_num: 0,
      order_week_price: 0,
      work_status: 1,
      //tab标签
      filterItem: {
        1: {name: '今日订单', page: 1, allLoaded: false, loading: false},
        2: {name: '明日订单', page: 1, allLoaded: false, loading: false}
      },
      //订单对象数组
      orderList: {
        1: [], 2: []
      },
      //当前标签索引
      currentTabIndex: 1,
      //改期modal
      mdDateVisible: false,
      //改期picker
      mdTimeVisible: false,
      //是否有未读消息
      message: 0
    }
  },
  async created(){
    if ($prod) {
      const string = device.platform;
      const oldVersion = AppVersion.version;
      const json = await this.$http.get(VERSION, null, {show: true, type: 'mini'});
      console.log(string)
      if (json.result === 1) {
        const newVersion = string === 'Android' ? json.data.store_android_beta : json.data.store_ios_beta;
        const url = string === 'Android' ? json.data.store_android_url : json.data.store_ios_url;
        const content = json.data.market_content;
        console.log(url)
        if (oldVersion !== newVersion && json.data.store_update_force === 1) {
          this.$modal({message: `为了不影响您的正常使用,请下载最新版本，更新内容: ${content}`, cancel: true,lock: true})
            .then(action => {
              window.location.assign(url)
              this.$toast('正在下载中,请稍后再用');
              navigator.app.exitApp();
            },()=>{
              navigator.app.exitApp();
            })
         }
      }
    }
  },
  async mounted() {
    this.$refs.homeTop.onload = () => {
      //若为登录状态
      if (this.currentUser.token) {
        //默认选中第一个
        this.getOrders({tab: 0}).then((jsonData) => {
          this.$set(this.orderList, 1, jsonData[1]);
          this.$set(this.orderList, 2, jsonData[2])
          this.filterItem[1].allLoaded = jsonData[1].length < 10;
          this.filterItem[2].allLoaded = jsonData[2].length < 10;
          this.currentTabIndex = 1;
          this.firstLoad = false;
        });
      }
    };
    transfer.$once('finished', ({order_id, arrIndex}) => {
      let index = this.currentTabIndex;
      this.orderList[index][arrIndex].order_status = 4;
    });
  },
  methods: {
    async getOrders({tab = this.currentTabIndex, page = 1, next = false, pull = false}) {
      let loadingObj = pull ? {} : {show: this.firstLoad, type: 'mini'};
      let json = await this.$http.post(GET_INDEX, {tab, page}, loadingObj);
      if (json.result === 1) {
        let jsonData;
        let {orders_week_num, order_week_price, work_status, message} = json.data;
        this.orders_week_num = orders_week_num;
        this.order_week_price = order_week_price;
        this.message = message;
        this.work_status = work_status;
        //加载完切换tab1
        if (tab === 1) {
          jsonData = json.data.today_orders;
        }
        //加载完切换tab2
        else if (tab === 2) {
          jsonData = json.data.tomorrow_orders;
        }
        //初次加载获取今日和明日得订单
        else {
          let {today_orders, tomorrow_orders} = json.data;
          //默认
          this.currentTabIndex = 1;
          jsonData = {1: today_orders, 2: tomorrow_orders};
        }
        return jsonData;
      }
      return null;
    },
    setOut(formData, index) {
      this.$modal({
        title: '温馨提示',
        message: '您确定开始服务吗？',
        cancel: false,
        lock: true
      }).then(async (action) => {
          let json = await this.$http.post(ORDER_TAKING, formData, {show: true, type: 'mini'});
          if (json.result === 1) {
            this.orderList[this.currentTabIndex][index].order_status = 3;
            this.$toast({message: '祝您顺利', position: 'bottom'});
          }
        }
      );
    },
    editWorkStatus() {
      let str;
      str = this.work_status ? '离' : '上';
      this.$modal({
        title: '提示',
        message: `您确认${str}线吗？`,
        cancel: false
      }).then(async (action) => {
        let status = this.work_status ? 0 : 1;
        let json = await this.$http.post(EDIT_WORK_STATUS, {status});
        // console.log(json)
        if (json.result === 1) {
          this.work_status = status;
        }
      })
    },
    orderAction(type, order_id, num) {
      let formData = {type, order_id};
      switch (type) {
        case 2:
          this.orderTaking(formData, num);
          break;
        case 3:
          this.setOut(formData, num);
          break;
        case 4:
          this.$router.push({name: 'serviceLog', params: {order_id, arrIndex: num}});
          break;
        default:
          break;
      }
    }
  },
  computed: {
    ...mapState([
      'currentUser'
    ])
  }
}
